<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" class="search-form">
        <el-form-item>
          <el-input
            v-model="queryParams.customerName"
            placeholder="请输入客户名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.customerType" placeholder="请选择客户类型" clearable size="small">
            <el-option label="企业" value="1" />
            <el-option label="个人" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
            <el-option label="启用" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 客户管理标题 -->
    <div class="customer-title">
      <h3></h3>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="table-operations">
      <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
      <el-button type="danger" size="small" :disabled="multiple" @click="handleDelete()">批量删除</el-button>
    </div>
    
    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="customerList"
      @selection-change="handleSelectionChange"
      border
      ref="table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="客户编号" align="center" prop="customerCode" min-width="100" />
      <el-table-column label="客户名称" align="center" prop="customerName" min-width="120" />
      <el-table-column label="客户类型" align="center" prop="customerType" min-width="100" />
      <el-table-column label="联系人" align="center" prop="contactPerson" min-width="100" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" min-width="120" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === '1' || scope.row.status === 1">启用</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页区域 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    
    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户编号" prop="customerCode">
          <div class="code-input-container">
            <el-input 
              v-model="form.customerCode" 
              placeholder="请输入客户编号" 
              disabled
              class="customer-code-input">
              <el-button slot="append" icon="el-icon-refresh" @click="getAutoCode" v-if="!form.id">自动编号</el-button>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="客户类型" prop="customerType">
          <el-select v-model="form.customerType" placeholder="请选择客户类型" style="width:100%">
            <el-option label="企业" value="1" />
            <el-option label="个人" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import { listCustomer, getCustomer, delCustomer, delCustomers, addCustomer, updateCustomer } from "@/api/basic/customer";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";
import Pagination from "@/components/Pagination";

export default {
  name: "Customer",
  components: {
    Pagination
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerCode: undefined,
        customerName: undefined,
        customerType: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerCode: [
          { required: true, message: "客户编号不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        customerType: [
          { required: true, message: "客户类型不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      // 构建查询参数
      const queryParams = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        customer_name: this.queryParams.customerName,
        customer_type: this.queryParams.customerType !== undefined ? parseInt(this.queryParams.customerType) : undefined,
        customer_status: this.queryParams.status
      };
      
      console.log('查询参数:', queryParams);
      
      listCustomer(queryParams)
        .then(response => {
          console.log('获取客户列表响应:', response);
          
          if (response.code === 200) {
            // 映射后端字段名到前端字段名
            this.customerList = (response.rows || []).map(item => ({
              id: item.customer_id,
              customerId: item.customer_id,
              customerCode: item.customer_code,
              customerName: item.customer_name,
              customerType: item.customer_type == 1 ? '企业' : '个人',
              contactPerson: item.customer_person,
              contactPhone: item.customer_phone,
              status: item.customer_status == 1 ? '1' : '0',
              cpStatus: item.cp_status,
              remarks: item.remarks
            }));
            
            this.total = response.total || 0;
            console.log('处理后的客户列表:', this.customerList);
          } else {
            this.$message.error(response.msg || '获取数据失败');
            this.customerList = [];
            this.total = 0;
          }
        })
        .catch(error => {
          console.error('获取客户列表失败:', error);
          this.$message.error('获取客户列表失败: ' + (error.message || '未知错误'));
          this.customerList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        customerCode: '',
        customerName: '',
        customerType: '1', // 默认值为企业，对应后端的1
        contactPerson: '',
        contactPhone: '',
        status: "1",
        remarks: ''
      };
      this.resetForm("form");
      // 重置自动编码状态
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        customerName: undefined,
        customerType: undefined,
        status: undefined
      };
      this.handleQuery();
    },
    
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 确保表单中的客户类型是正确的默认值
      this.form = {
        customerCode: '',
        customerName: '',
        customerType: '1',
        contactPerson: '',
        contactPhone: '',
        status: '1',
        remarks: ''
      };
      this.open = true;
      this.title = "添加客户";
      // 默认设置状态为启用
      this.form.status = '1';
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || row.customerId;
      
      // 调试日志，帮助排查ID问题
      console.log("编辑客户原始数据:", row);
      console.log("客户ID:", id);
      
      // 直接从行数据映射字段
      this.form = {
        id: id,
        customerCode: row.customerCode,
        customerName: row.customerName,
        customerType: row.customerType === '企业' || row.customerType === 1 || row.customerType === '1' ? '1' : '0',
        contactPerson: row.contactPerson,
        contactPhone: row.contactPhone,
        status: row.status,
        remarks: row.remarks
      };
      
      // 确保customerType和status字段的值是正确的
      if (this.form.customerType === '企业') {
        this.form.customerType = '1';
      } else if (this.form.customerType === '个人') {
        this.form.customerType = '0';
      }
      
      console.log("表单数据:", this.form);
      
      this.open = true;
      this.title = "修改客户";
    },
    
    // 获取自动编码
    getAutoCode() {
      // 如果是编辑模式且已有客户编号，则不重新获取
      if (this.form.id && this.form.customerCode) {
        console.log("编辑模式，保留原客户编号:", this.form.customerCode);
        return;
      }
      
      this.$modal.loading("正在获取自动编码...");
      
      // 调用获取自动编码接口，传入编码类型参数值为17（客户编号）
      getAutoNumbers(17).then(response => {
        this.$modal.closeLoading();
        
        console.log("自动编码API返回数据:", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.customerCode = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.customerCode = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.customerCode = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.customerCode = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.customerCode = "KH" + new Date().getTime(); // 生成临时编号
          }
        } else {
          console.error("获取自动编号失败，响应：", response);
          this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取自动编号失败:", error);
        this.$modal.msgError("获取自动编号失败: " + (error.message || "未知错误"));
      });
    },
    
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 如果是新增模式且有客户编号，在提交前获取真正的编号
          if (!this.form.id && this.form.customerCode) {
            try {
              const response = await getAutoNumbersConsume(17);
              if (typeof response === 'string') {
                this.form.customerCode = response;
              } else if (response && response.msg) {
                this.form.customerCode = response.msg;
              }
            } catch (error) {
              this.$modal.msgError('获取最终客户编号失败');
              return;
            }
          }
          
          // 最后确认编号存在
          if (!this.form.customerCode) {
            this.$modal.msgError("客户编号不能为空");
            return;
          }
          
          // 创建发送到后端的数据对象，确保字段名映射正确
          const submitData = {
            customer_id: this.form.id, // 如果是编辑，则包含ID
            customer_code: this.form.customerCode,
            customer_name: this.form.customerName,
            // 将字符串值转换为数字
            customer_type: parseInt(this.form.customerType),
            customer_person: this.form.contactPerson,
            customer_phone: this.form.contactPhone,
            customer_status: parseInt(this.form.status),
            remarks: this.form.remarks
          };
          
          // 详细日志用于调试
          console.log('提交的客户数据:', submitData);
          console.log('客户类型值:', submitData.customer_type, '类型:', typeof submitData.customer_type);
          
          if (this.form.id) {
            updateCustomer(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "修改失败");
              }
            });
          } else {
            addCustomer(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "新增失败");
              }
            });
          }
        }
      });
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      // 从行数据或选中的ID数组获取ID
      let ids = [];
      let names = [];
      
      if (row) {
        // 单个删除
        const id = row.id || row.customerId;
        if (id) {
          ids.push(id);
          names.push(row.customerName || '未知客户');
        }
      } else {
        // 批量删除
        ids = this.ids;
        
        // 获取所有选中行的名称
        const selectedRows = this.$refs.table ? this.$refs.table.selection : [];
        if (selectedRows && selectedRows.length > 0) {
          names = selectedRows.map(row => row.customerName || '未知客户');
        } else {
          names = ['选中的客户'];
        }
      }
      
      if (ids.length === 0) {
        this.$message.warning('请选择需要删除的客户');
        return;
      }
      
      // 根据是否为批量删除显示不同的确认消息
      const title = ids.length === 1 
        ? `是否确认删除客户"${names[0]}"?` 
        : `是否确认删除选中的${ids.length}个客户?`;
        
      this.$confirm(title, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 根据ID数量决定使用单个删除还是批量删除API
        let deletePromise;
        if (ids.length === 1) {
           deletePromise=delCustomer(ids[0]);
        } else {
          // 将ID数组转换为逗号分隔的字符串
          const idsString = ids.join(',');
          deletePromise=delCustomers(idsString);
        }
         return deletePromise;
      }).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        } else {
          this.$modal.msgError(response.msg || "删除失败");
        }
      }).catch(error => {
        console.error("删除客户失败:", error);
        if (error !== 'cancel') {
          this.$modal.msgError("删除失败: " + (error.message || "未知错误"));
        }
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.search-container {
  background-color: #ffffff;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.customer-title {
  margin-bottom: 15px;
}

.customer-title h3 {
  font-size: 18px;
  margin: 0;
  padding: 0;
}

.table-operations {
  margin-bottom: 15px;
}

.el-table {
  margin-top: 15px;
  background-color: #ffffff;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.text-center {
  text-align: center;
}

.code-input-container {
  display: flex;
  align-items: center;
}

.customer-code-input {
  width: 100%;
}
</style>